<div class="layuimini-container layuimini-page-anim">
  <div class="layuimini-main">
    
    <table class="layui-hide" id="ck-table" lay-filter="ck-table"></table>

    <script type="text/html" id="toolbarDemo">
      <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="addCookie">
          <i class="layui-icon layui-icon-user"></i>
          手动添加
        </button>
        <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="checkAllCookie">
          <i class="layui-icon layui-icon-vercode"></i>
          校验Cookie
        </button>
        <button class="layui-btn layui-btn-sm layui-btn-warm" lay-event="delExpireCookie">
          <i class="layui-icon layui-icon-delete"></i>
          删除失效Cookie
        </button>
        <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="downloadApp">
          <i class="layui-icon layui-icon-download-circle"></i>
          下载App
        </button>
        <button class="layui-btn layui-btn-sm layui-bg-black" lay-event="operation">
          <i class="layui-icon layui-icon-tips"></i>
          使用说明
        </button>
      </div>
    </script>

    <script type="text/html" id="barDemo">
      <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
      <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"
        >删除</a
      >
      <!-- 这里同样支持 laytpl 语法，如： -->
      {{# if(d.status == 1){ }}
      <a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="disable">禁用</a>
      {{# } }} 
      {{# if(d.status == 0){ }}
      <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="enable">启用</a>
      {{# } }}
    </script>

    <script type="text/html" id="statusTpl">
      {{# if(d.status == 0){ }}
      <span style="color: #F581B1;">{{ '禁用' }}</span>
      {{# } else { }} {{ '正常' }} {{# } }}
    </script>

    <script type="text/html" id="expireTpl">
      {{# if(d.expire == 1){ }}
      <span style="color: #F581B1;">{{ '是' }}</span>
      {{# } else { }} {{ '否' }} {{# } }}
    </script>
  </div>
</div>

<style>
  .layui-table,
  .layui-table-view {
    margin: 0px;
  }
</style>

<script type="text/javascript">
  layui.use(["table", "dropdown", "soulTable"], function () {
    var table = layui.table;
    var dropdown = layui.dropdown;
    var soulTable = layui.soulTable;
    var insTable = table.render({
      elem: "#ck-table",
      id: "cookie-table",
      url: "/api/getCookieList",
      toolbar: "#toolbarDemo", //开启头部工具栏，并为其绑定左侧模板
      defaultToolbar: ['exports'],
      title: "Cookie数据表",
      cols: [
        [
          // { type: "checkbox", fixed: "left" },
          {
            field: "id",
            title: "ID",
            width: 60,
            fixed: "left",
            sort: true,
            templet: function (d) {
              return d.LAY_INDEX;
            },
          },
          {
            field: "cookie",
            title: "Cookie",
            edit: "text",
            width: 300,
          },
          // {
          //   field: "jvalue",
          //   title: "京豆",
          //   width: 100,
          // },
          {
            field: "date",
            title: "更新时间",
            width: 170,
            sort: true,
          },
          {
            field: "expire",
            title: "是否过期",
            width: 90,
            templet: "#expireTpl",
          },
          {
            field: "status",
            title: "状态",
            width: 100,
            templet: "#statusTpl",
          },
          {
            field: "remarks",
            title: "备注",
            width: 160,
            edit: "text",
          },
          {
            field: "options",
            // fixed: "right",
            title: "操作",
            templet: "#barDemo",
            // align: "center",
            // width: 200,
          },
        ],
      ],
      page: true,
      method: "post",
      limit: 10,
      request: {
        pageName: "page", //页码的参数名称，默认：page
        limitName: "limit", //每页数据量的参数名，默认：limit
      },
      parseData: function (res) {
        res.data = res.data.map(function (d) {
          d["options"] = "";
          return d;
        });
        return res;
      },
      rowDrag: {trigger: 'row', done: function(obj) {
            // 完成时（松开时）触发
            // 如果拖动前和拖动后无变化，则不会触发此方法
            // console.log(obj.row) // 当前行数据
            // console.log(obj.cache) // 改动后全表数据
            // console.log(obj.oldIndex) // 原来的数据索引
            // console.log(obj.newIndex) // 改动后数据索引
            $.post("/api/sortCookie", { type: obj.newIndex > obj.oldIndex ? 'moveDown' : 'moveUp', oldIndex: obj.oldIndex, newIndex: obj.newIndex }, function (result) {
              // console.log(result);
            });
      }},
      done: function (res, curr, count) {
        // 在 done 中开启
        soulTable.render(this)
        exportData = res.data.map((item) => {
          return { cookie: item.cookie }
        });
      }
    });

    //头工具栏事件
    table.on("toolbar(ck-table)", function (obj) {
      var checkStatus = table.checkStatus(obj.config.id);
      switch (obj.event) {
        case "getCheckData":
          var data = checkStatus.data;
          layer.alert(JSON.stringify(data));
          break;
        case "getCheckLength":
          var data = checkStatus.data;
          layer.msg("选中了：" + data.length + " 个");
          break;
        case "isAll":
          layer.msg(checkStatus.isAll ? "全选" : "未全选");
          break;
        case "addCookie":
          layer.prompt(
            {
              maxlength: 10000,
              formType: 2,
              title: "请输入Cookie,支持批量添加,一行一个!",
              area: ["450px", "140px"], //自定义文本域宽高
            },
            function (value, index, elem) {
              let code = value.split(/[(\r\n)\r\n]+/); // 根据换行或者回车进行识别
              code.forEach((item, index) => {
                // 删除空项
                if (!item) {
                  code.splice(index, 1);
                }
              });
              code = Array.from(new Set(code)); // 去重
              layer.close(index);
              (async () => {
                for (var i = 0; i < code.length; i++) {
                  await $.post("/api/updateCookie", { cookie: code[i] },function (result) {
                      layer.msg(result.msg);
                    }
                  );
                }
                table.reload("cookie-table");
              })();
            }
          );
          break;
        case "downloadApp":
          window.location.href =
            "https://gitee.com/tbkuashidai/jd-base/raw/master/app/jd-cookie.apk";
          break;
        case "checkAllCookie":
          var index = layer.load(1, {
            shade: [0.5, "#fff"], //0.1透明度的白色背景
          });
          $.post("/api/checkAllCookie", {}, function (result) {
            layer.msg(result.msg);
            table.reload("cookie-table");
            layer.close(index);
          });
          break;
        case "delExpireCookie":
          $.post("/api/delExpireCookie", {}, function (result) {
            layer.msg(result.msg);
            table.reload("cookie-table");
          });
          break;
        case "operation":
          layer.open({
            type: 0,
            title: "使用说明",
            shade: 0,
            maxmin: true,
            content:
              '1.如果首次使用异常、检查config文件夹下面是否有cookie.json文件,如果有请删除再使用.</br>2.配合App使用,首次打开App点击右上角云朵图标输入你面板管理地址,然后登录账号会自动更新Cookie到此面板!',
          });
          break;
      }
    });

    //触发单元格编辑
    table.on("edit(ck-table)", function (obj) {
      updateCookie(obj.data);
    });

    //监听行工具事件
    table.on("tool(ck-table)", function (obj) {
      var data = obj.data;
      delete data.options;
      var rowIndex = $(obj.tr).attr("data-index");
      // console.log(rowIndex)
      if (obj.event === "del") {
        layer.confirm(`是否确定删除${data.remarks || ""}?`, function (index) {
          $.post(
            "/api/delCookie",
            { cookie: JSON.stringify(data) },
            function (result) {
              obj.del();
              table.reload("cookie-table");
              layer.msg(result.msg);
            }
          );
          layer.close(index);
        });
      } else if (obj.event === "edit") {
        layer.prompt(
          {
            title: "Cookie编辑",
            formType: 2,
            value: data.cookie,
            area: ["450px", "40px"], //自定义文本域宽高
          },
          function (value, index) {
            updateCookie(data);
            obj.update({ cookie: value });
            layer.close(index);
          }
        );
      } else if (obj.event === "disable" || obj.event === "enable") {
        data.status = obj.event === "disable" ? '0' : '1';
        $.post(
          "/api/modifyCookie",
          { cookie: JSON.stringify(data) },
          function (result) {
            obj.update({ ...data, options: data.status });
            layer.msg(result.msg);
          }
        );
      }
    });

    function updateCookie(data) {
      $.post(
        "/api/modifyCookie",
        { cookie: JSON.stringify(data) },
        function (data) {
          layer.msg(data.msg);
        }
      );
    }
  });
</script>
